﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Windows.Forms;
using BusinessObjects.Constants;
using BusinessServices;
using CarLeaseManageSystem.Properties;
using Core.Utilities;
using DataEntities;

namespace CarLeaseManageSystem
{
    public partial class FormLeaseMana : Form
    {
        private readonly ChuZuService _chuZuService;
        private readonly KeHuService _keHuService;
        private readonly XuZuService _xuZuService;
        private readonly CarService _carService;
        private readonly YuZuService _yuZuService;

        public FormLeaseMana()
        {
            _chuZuService = new ChuZuService();
            _keHuService = new KeHuService();
            _xuZuService = new XuZuService();
            _carService = new CarService();
            _yuZuService = new YuZuService();
            InitializeComponent();
        }

        //窗口的初始化
        private void FormLeaseMana_Load(object sender, EventArgs e)
        {
            CacheKeHuInfo();
            CacheFreeCarsInfo();
            numericYH.Value = numericYJ.Value = numericYF.Value = numericRF.Value = 0;
            dateStart.Value = DateTime.Now.Date; dateEnd.Value = DateTime.Now.Date.AddDays(1);
            pictNewCar.Image = Properties.Resources.car2;
        }

        //新建续租信息
        private void btnXZ_Click(object sender, EventArgs e)
        {
            if (numYFXZJE.Value == 0)
            {
                MessageBox.Show(XuZuConstant.XuZuInfoLost, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //创建新实体
            var newXuZuInfo = new XuZuInfo
            {
                iCZDId = (int)labChuZuInfo.Tag,
                dXZJE = (double)numYFXZJE.Value,
                tOldDate = dateTimePickerEnd.Value,
                tNewDate = dateNewDate.Value
            };

            //添加续租单
            newXuZuInfo = _xuZuService.Add(newXuZuInfo);

            //如果续租单编号大于0则添加成功
            if (newXuZuInfo.iXZDId > 0)
            {
                MessageBox.Show(XuZuConstant.Succeed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //更新出租单的续租状态
                _chuZuService.Update(newXuZuInfo.iCZDId, chuZuInfo => chuZuInfo.bXZ = true);
                //重新加载数据
                tabControl1_SelectedIndexChanged(sender, e);
                //关闭续租面板
                panel1.Visible = false;
            }
            else
            {
                MessageBox.Show(XuZuConstant.Failed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //打开续租面板
        private void btnGoXZ_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
            dateNewDate.Value = dateTimePickerEnd.Value.AddDays(1);
        }

        //关闭续租面板
        private void btnClose_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        List<KeHuInfo> UnRentalKeHuInfo = new List<KeHuInfo>();
        //缓存未租客户和预租客户
        private void CacheKeHuInfo()
        {
            comBoxClient.Items.Clear();
            UnRentalKeHuInfo.Clear();

            var newKeHu = _keHuService.GetNewKeHuInfo();
            var yuZuKeHu = _keHuService.GetYuZuKeHuInfo();

            if (newKeHu.Count > 0)
            {
                comBoxClient.Items.Add("***未租客户***");
                UnRentalKeHuInfo.Add(new KeHuInfo());
                foreach (KeHuInfo keHu in newKeHu)
                {
                    comBoxClient.Items.Add(string.Format("{0}({1})", keHu.sName, keHu.sIdCard));
                    UnRentalKeHuInfo.Add(keHu);
                }
            }

            if (yuZuKeHu.Count > 0)
            {
                comBoxClient.Items.Add("***预租客户***");
                UnRentalKeHuInfo.Add(new KeHuInfo());
                foreach (KeHuInfo keHu in yuZuKeHu)
                {
                    comBoxClient.Items.Add(string.Format("{0}({1})", keHu.sName, keHu.sIdCard));
                    UnRentalKeHuInfo.Add(keHu);
                }
            }
        }

        List<CarInfo> FreeCars = new List<CarInfo>();
        ComboBox comBoxCarBackup = new ComboBox();
        //缓存没有报废,没有预租,没有出租的空闲车辆
        private void CacheFreeCarsInfo()
        {
            var freeCars = _carService.GetFreeCars();

            comBoxCar.Items.Clear();
            FreeCars.Clear();

            foreach (CarInfo carInfo in freeCars)
            {
                var item = string.Format("{0}({1})", carInfo.sCType, carInfo.sCPId);
                comBoxCar.Items.Add(item);
                comBoxCarBackup.Items.Add(item);
                FreeCars.Add(carInfo);
            }
        }

        //创建出租单 
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (numericRF.Value == 0 || comBoxClient.SelectedItem == null || comBoxCar.SelectedItem == null)
            {
                MessageBox.Show(ChuZuConstant.BaseInfoLost, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int carIndex = comBoxCar.SelectedIndex;
            int keHuIndex = comBoxClient.SelectedIndex;
            int carId = 0;
            int yuZuId = 0;
            KeHuInfo keHuInfo = UnRentalKeHuInfo[keHuIndex];

            //如果客户有预租单，则加载其预租的车辆信息
            if (keHuInfo.YuZuInfo.HasLoadedOrAssignedValues && keHuInfo.YuZuInfo.Count > 0)
            {
                var yuZuInfo = keHuInfo.YuZuInfo.First();
                yuZuId = yuZuInfo.iYZDId;
                carId = yuZuInfo.iCarid;
            }
            else
            {
                carId = FreeCars[carIndex].iCarid;
            }
            //创建出租单实体
            var chuZuInfo = new ChuZuInfo
            {
                iKeHuId = keHuInfo.iKeHuId,
                iCarid = carId,
                dRiFuJE = (double)numericRF.Value,
                dYuFuJE = (double)numericYF.Value,
                dYaJing = (double)numericYJ.Value,
                dYouHuiJE = (double)numericYH.Value,
                dShiFuJE = (double)numSF.Value,
                tStartDate = dateStart.Value,
                tEndDate = dateEnd.Value
            };
            //添加出租单到数据库
            chuZuInfo = _chuZuService.Add(chuZuInfo);
            //如果出租单id大于0则添加成功
            if (chuZuInfo.iCZDId > 0)
            {
                MessageBox.Show(ChuZuConstant.Succeed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //删除预租单 
                if (yuZuId > 0)
                {
                    _yuZuService.Delete(yuZuId);
                }
                //重新加载数据
                FormLeaseMana_Load(sender, e);
            }
            else
            {
                MessageBox.Show(ChuZuConstant.Failed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //选择租车客户
        private void comBoxClient_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comBoxClient.SelectedItem != null)
            {
                btnOk.Enabled = true;
            }
            if (comBoxClient.SelectedItem.ToString() == "***未租客户***" || comBoxClient.SelectedItem.ToString() == "***预租客户***")
            {
                comBoxClient.SelectedIndex++;
            }

            int keHuIndex = comBoxClient.SelectedIndex;
            KeHuInfo keHuInfo = UnRentalKeHuInfo[keHuIndex];

            comBoxCar.Items.Clear();
            pictNewCar.Image = Properties.Resources.car2;
            //如果客户有预租车辆，则将其预租信息加载到控件
            if (keHuInfo.YuZuInfo.HasLoadedOrAssignedValues && keHuInfo.YuZuInfo.Count > 0)
            {
                var yuZuInfo = keHuInfo.YuZuInfo.First();
                comBoxCar.Items.Add(yuZuInfo.CarInfo.sCType);
                comBoxCar.SelectedIndex = 0;
                numericYF.Value = (decimal)(yuZuInfo.dYuFuJE);
                pictNewCar.Image = yuZuInfo.CarInfo.mCPhoto.ToImage();
                dateStart.Value = yuZuInfo.tYZDate.AddDays(1);
            }
            else
            {
                foreach (object t in comBoxCarBackup.Items)
                {
                    comBoxCar.Items.Add(t);
                }
            }
        }

        //切换车辆时更换车辆照片
        private void comBoxCar_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                pictNewCar.Image = FreeCars[comBoxCar.SelectedIndex].mCPhoto.ToImage();
            }
            catch { }
        }

        //开始日期
        private void dateStart_ValueChanged(object sender, EventArgs e)
        {
            dateEnd.Value = dateStart.Value.AddDays(1);
            numDays.Value = Decimal.Round((Decimal)(dateEnd.Value - dateStart.Value).TotalDays, 0);
            numYF.Value = Decimal.Round((numDays.Value * numericRF.Value), 2);
        }

        //结束日期
        private void dateEnd_ValueChanged(object sender, EventArgs e)
        {
            if (dateEnd.Value <= dateStart.Value)
            {
                dateEnd.Value = dateStart.Value.AddDays(1);
                MessageBox.Show(ChuZuConstant.TimeEndError, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                numDays.Value = Decimal.Round((Decimal)(dateEnd.Value - dateStart.Value).TotalDays, 0);
                numYF.Value = Decimal.Round((numDays.Value * numericRF.Value), 2);
            }
        }

        //private List<ChuZuInfo> _chuZuInfo = new List<ChuZuInfo>();
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabExist)
            {
                //获取出租表中的所有信息
                //_chuZuInfo = _chuZuService.GetAll();
                LoadLeasedClient();
            }
        }

        List<KeHuInfo> liLeasedKH = new List<KeHuInfo>();
        private void LoadLeasedClient()
        {
            var keHuInfo = _keHuService.GetKeHuInfoByChuZuRecord();
            listViewExist.Items.Clear();
            liLeasedKH.Clear();
            foreach (KeHuInfo keHu in keHuInfo)
            {
                var newItem = new ListViewItem { Name = keHu.sName, Text = keHu.sName, Tag = keHu.iKeHuId };
                newItem.SubItems.Add(keHu.sIdCard);
                listViewExist.Items.Add(newItem);
                liLeasedKH.Add(keHu);
            }
        }

        private void txtBoxSearName_TextChanged(object sender, EventArgs e)
        {
            listViewExist.Items.Clear();
            foreach (KeHuInfo keHu in liLeasedKH.Where(keHu => keHu.sName.Contains(txtBoxSearName.Text)))
            {
                ListViewItem newItem = new ListViewItem { Tag = keHu.iKeHuId, Text = keHu.sName };
                newItem.SubItems.Add(keHu.sIdCard);
                listViewExist.Items.Add(newItem);
            }
        }

        private List<ChuZuInfo> _cacheChuZuInfoForKeHu = new List<ChuZuInfo>();
        private void listViewExist_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
            {
                return;
            }

            var keHuId = (int)e.Item.Tag;
            if (_cacheChuZuInfoForKeHu.Count == 0 || _cacheChuZuInfoForKeHu.First().iKeHuId != keHuId)
            {
                _cacheChuZuInfoForKeHu = _chuZuService.GetChuZuInfoByKeHuId(keHuId);
            }

            if (comBoxCZFilter.SelectedIndex == -1)
            {
                comBoxCZFilter.SelectedIndex = 2;
            }
            else
            {
                comBoxCZFilter_SelectedIndexChanged(sender, e);
            }

            //确保切换用户时关闭续租面板
            panel1.Visible = false;
        }

        private void comBoxCZFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            IEnumerable<ChuZuInfo> afterFilter;
            switch (comBoxCZFilter.SelectedIndex)
            {
                case 0:
                    afterFilter = _cacheChuZuInfoForKeHu.Where(o => !o.bCZZF);
                    break;
                case 1:
                    afterFilter = _cacheChuZuInfoForKeHu.Where(o => o.bCZZF);
                    break;
                default:
                    afterFilter = _cacheChuZuInfoForKeHu;
                    break;
            }
            BindingDataToControls(afterFilter);
        }

        private void BindingDataToControls(IEnumerable<ChuZuInfo> afterFilter)
        {
            ClearDataBindings();
            if (afterFilter.Count() == 0)
            {
                return;
            }
            var bindingSource = new BindingSource();
            bindingSource.DataSource = GetBindingSource(afterFilter);
            bindingNavigator.BindingSource = bindingSource;
            labChuZuInfo.DataBindings.Add(new Binding("Tag", bindingSource, "iCZDId"));
            labelName.DataBindings.Add(new Binding("Text", bindingSource, "sName"));
            labelName.DataBindings.Add(new Binding("Tag", bindingSource, "iKeHuId"));
            labelCar.DataBindings.Add(new Binding("Text", bindingSource, "sCType"));
            labelCar.DataBindings.Add(new Binding("Tag", bindingSource, "iCarid"));
            txtBoxPrepay2.DataBindings.Add(new Binding("Text", bindingSource, "dYuFuJE"));
            textBoxYJ.DataBindings.Add(new Binding("Text", bindingSource, "dYaJing"));
            textBoxYH.DataBindings.Add(new Binding("Text", bindingSource, "dYouHuiJE"));
            textBoxRF.DataBindings.Add(new Binding("Text", bindingSource, "dRiFuJE"));
            dateTimePickerStart.DataBindings.Add(new Binding("Value", bindingSource, "tStartDate"));

            numTS.DataBindings.Add(new Binding("Value", bindingSource, "TS"));
            numYF2.DataBindings.Add(new Binding("Value", bindingSource, "YingFu"));
            numSF2.DataBindings.Add(new Binding("Value", bindingSource, "dShiFuJE"));
            labXZ.DataBindings.Add(new Binding("Text", bindingSource, "IsXZ"));
            pictureBoxCar.DataBindings.Add(new Binding("Image", bindingSource, "CarImg"));

            //如果客户已续租则结束日期为续租后的日期,如果没有则为实际结束日期
            dateTimePickerEnd.DataBindings.Add(new Binding("Value", bindingSource, "EndDate"));

            btnGoXZ.DataBindings.Add(new Binding("Text", bindingSource, "GoXZText"));
            btnGoXZ.DataBindings.Add(new Binding("Enabled", bindingSource, "GoXZEnabled"));
        }

        private void ClearDataBindings()
        {
            labChuZuInfo.DataBindings.Clear();
            labelName.DataBindings.Clear();
            labelCar.DataBindings.Clear();
            txtBoxPrepay2.DataBindings.Clear();
            textBoxYJ.DataBindings.Clear();
            textBoxYH.DataBindings.Clear();
            textBoxRF.DataBindings.Clear();
            dateTimePickerStart.DataBindings.Clear();
            numTS.DataBindings.Clear();
            numYF2.DataBindings.Clear();
            numSF2.DataBindings.Clear();
            labXZ.DataBindings.Clear();
            pictureBoxCar.DataBindings.Clear();
            dateTimePickerEnd.DataBindings.Clear();
            btnGoXZ.DataBindings.Clear();
            btnGoXZ.DataBindings.Clear();

            labelName.Text = "[Name]";
            labelCar.Text = "[Car]";
            txtBoxPrepay2.Text = string.Empty;
            textBoxYJ.Text = string.Empty;
            textBoxYH.Text = string.Empty;
            textBoxRF.Text = string.Empty;
            dateTimePickerStart.Value = DateTime.Now;
            numTS.Value = default(decimal);
            numYF2.Value = default(decimal);
            numSF2.Value = default(decimal);
            labXZ.Text = string.Empty;
            pictureBoxCar.Image = Resources.car2;
            dateTimePickerEnd.Value = DateTime.Now;
            btnGoXZ.Enabled = false;
            bindingNavigator.BindingSource=null;
        }

        private object GetBindingSource(IEnumerable<ChuZuInfo> chuZuInfo)
        {
            return chuZuInfo.Select(cz =>
            {
                var endDate = cz.bXZ ? cz.XuZuInfo.Max(x => x.tNewDate) : cz.tEndDate;
                var days = (endDate - cz.tStartDate).Days;
                return new
                    {
                        cz.iCZDId,
                        cz.KeHuInfo.sName,
                        cz.iKeHuId,
                        cz.CarInfo.sCType,
                        cz.iCarid,
                        cz.dYuFuJE,
                        cz.dYaJing,
                        cz.dYouHuiJE,
                        cz.dRiFuJE,
                        cz.tStartDate,
                        cz.dShiFuJE,
                        EndDate = endDate,
                        TS = days,
                        YingFu = cz.dRiFuJE * days,
                        CarImg = cz.CarInfo.mCPhoto.ToImage(),
                        IsXZ = cz.bXZ ? "已续" : "未续",
                        GoXZText = cz.bCZZF ? "已结算" : "去续租",
                        GoXZEnabled = !cz.bCZZF,
                    };
            }).AsQueryable();
        }

        private void dateNewDate_ValueChanged(object sender, EventArgs e)
        {
            //计算天数
            numXZDays.Value = Decimal.Round((Decimal)(dateNewDate.Value - dateTimePickerEnd.Value).TotalDays, 0);

            //计算应付续租金
            numYFXZJE.Value = numXZDays.Value * Decimal.Parse(textBoxRF.Text);
        }

    }
}